<script setup lang="ts">
import { registerAPI, type RegisterData } from '@/apis/user'
import { showLoadingToast, showSuccessToast } from 'vant'
import { ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const username = ref('')
const password = ref('')

const onSubmit = async (values: RegisterData) => {
  try {
    // 显示加载中
    showLoadingToast({
      message: '注册中...', // 提示信息
      forbidClick: true, // 禁止点击
    })
    // 往后台发送注册请求了
    await registerAPI(values)
    // 注册成功
    showSuccessToast('注册成功')
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('注册失败:', error)
  }
}
</script>

<template>
  <div class="register-view">
    <!-- 导航栏部分 -->
    <van-nav-bar title="面经注册" />

    <!-- 表单部分 -->
    <van-form @submit="onSubmit">
      <!-- 输入框组件 -->
      <!-- \w 字母数字_   \d 数数字0-9 -->
      <van-field
        v-model="username"
        name="username"
        label="用户名"
        placeholder="用户名"
        autocomplete="username"
        :rules="[
          { required: true, message: '请填写用户名' },
          { pattern: /^\w{5,}$/, message: '用户名至少包含5个字符' },
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="password"
        label="密码"
        placeholder="密码"
        autocomplete="new-password"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\w{6,}$/, message: '密码至少包含6个字符' },
        ]"
      />
      <div style="margin: 16px">
        <van-button block type="primary" native-type="submit"> 注册 </van-button>
      </div>
    </van-form>
    <router-link class="link" to="/login">有账号，去登录</router-link>
  </div>
</template>

<style lang="scss" scoped>
.link {
  color: #069;
  font-size: 12px;
  padding-right: 20px;
  float: right;
}
</style>
